// Copyright 2010 Alexandre Tristan St-Cyr <tristan.stcyr@gmail.com>

package com.codeplex.loadjava.model;

import org.objectweb.asm.Type;

public class TypeReference {
	
	private Type type;
	
	public TypeReference(Type type) {
		this.type = type;
	}
	
	public TypeReference(String descriptor) {
		this.type = Type.getType(descriptor);
	}
	
	public String getDescriptor()
	{
		return this.type.getDescriptor();
	}
	
	private String getElementTypeDescriptor()
	{
		return (this.type.getSort() == Type.ARRAY ?
				this.type.getElementType() : this.type)
				.getDescriptor();
	}
	
	public char getTypeKind()
	{
		return this.getElementTypeDescriptor().charAt(0);
	}
	
	public int getArrayDimensions()
	{
		return (this.type.getSort() == Type.ARRAY ?
				this.type.getDimensions() : 0);
	}
	
	public JavaClass getJavaClass()
	{
		Type elementType = type.getSort() == Type.ARRAY ? 
				this.type.getElementType() : this.type;
		return elementType.getSort() == Type.OBJECT ?
				new JavaClass(elementType.getInternalName()) : null;
	}
	
	public Type getType()
	{
		return this.type;
	}
	
	@Override
	public int hashCode()
	{
		return this.type.getDescriptor().hashCode();
	}
	
	@Override
	public boolean equals(Object o) {
		if (!this.getClass().isInstance(o))
			return false;
		TypeReference otherType = (TypeReference)o;
		return otherType.type.equals(this.type);
	}
	
	@Override
	public String toString()
	{
		return this.type.getDescriptor();
	}
}
